<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>删除功能调试</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .test-section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #007bff;
        }
        .test-section h3 {
            margin-top: 0;
            color: #007bff;
        }
        button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background: #0056b3;
        }
        button.danger {
            background: #dc3545;
        }
        button.danger:hover {
            background: #c82333;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            border-radius: 5px;
            white-space: pre-wrap;
            font-family: 'Courier New', monospace;
            font-size: 14px;
        }
        .success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .info {
            background: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        .auth-status {
            padding: 10px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .auth-true {
            background: #d4edda;
            color: #155724;
        }
        .auth-false {
            background: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 删除收藏功能调试工具</h1>
        
        <!-- 认证状态 -->
        <div id="authStatus" class="auth-status">
            <h3>认证状态检查</h3>
            <p id="authInfo">检查中...</p>
            <button onclick="checkAuth()">重新检查认证</button>
            <button onclick="clearAuth()">清除认证</button>
        </div>

        <!-- 测试1: 获取收藏列表 -->
        <div class="test-section">
            <h3>📋 测试1: 获取收藏列表</h3>
            <p>首先获取当前用户的收藏列表，用于后续删除测试</p>
            <button onclick="getBookmarks()">获取收藏列表</button>
            <div id="bookmarksResult" class="result"></div>
        </div>

        <!-- 测试2: 手动删除测试 -->
        <div class="test-section">
            <h3>🗑️ 测试2: 手动删除测试</h3>
            <p>输入收藏ID进行删除测试</p>
            <div class="form-group">
                <label for="bookmarkId">收藏ID:</label>
                <input type="number" id="bookmarkId" placeholder="输入要删除的收藏ID">
            </div>
            <button class="danger" onclick="testDelete()">删除收藏</button>
            <div id="deleteResult" class="result"></div>
        </div>

        <!-- 测试3: 原始API测试 -->
        <div class="test-section">
            <h3>🔧 测试3: 原始API测试</h3>
            <p>直接测试删除API的原始响应</p>
            <div class="form-group">
                <label for="rawBookmarkId">收藏ID:</label>
                <input type="number" id="rawBookmarkId" placeholder="输入要删除的收藏ID">
            </div>
            <button class="danger" onclick="testRawDelete()">原始删除API测试</button>
            <div id="rawDeleteResult" class="result"></div>
        </div>

        <!-- 测试4: 调试API测试 -->
        <div class="test-section">
            <h3>🐛 测试4: 调试API测试</h3>
            <p>使用专门的调试API，包含详细的调试信息</p>
            <div class="form-group">
                <label for="debugBookmarkId">收藏ID:</label>
                <input type="number" id="debugBookmarkId" placeholder="输入要删除的收藏ID">
            </div>
            <button class="danger" onclick="testDebugDelete()">调试删除API</button>
            <div id="debugDeleteResult" class="result"></div>
        </div>

        <!-- 测试5: 网络连接测试 -->
        <div class="test-section">
            <h3>🌐 测试5: 网络连接测试</h3>
            <p>测试API端点的连接性</p>
            <button onclick="testConnection()">测试连接</button>
            <div id="connectionResult" class="result"></div>
        </div>
    </div>

    <script>
        // 工具函数
        function showResult(elementId, content, type = 'info') {
            const element = document.getElementById(elementId);
            element.textContent = content;
            element.className = `result ${type}`;
        }

        function formatResponse(response, status, headers) {
            return `状态码: ${status}
响应头: ${JSON.stringify([...headers.entries()], null, 2)}
响应内容: ${response}`;
        }

        // 认证检查
        async function checkAuth() {
            const token = localStorage.getItem('auth_token');
            const authInfo = document.getElementById('authInfo');
            const authStatus = document.getElementById('authStatus');
            
            if (!token) {
                authInfo.textContent = '❌ 未找到认证令牌，请先登录';
                authStatus.className = 'auth-status auth-false';
                return false;
            }

            try {
                const response = await fetch('./api/auth.php?action=verify', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });
                
                const data = await response.json();
                
                if (data.success && data.data.valid) {
                    authInfo.textContent = `✅ 认证有效 - 用户: ${data.data.user.username}`;
                    authStatus.className = 'auth-status auth-true';
                    return true;
                } else {
                    authInfo.textContent = '❌ 认证令牌无效或已过期';
                    authStatus.className = 'auth-status auth-false';
                    return false;
                }
            } catch (error) {
                authInfo.textContent = `❌ 认证检查失败: ${error.message}`;
                authStatus.className = 'auth-status auth-false';
                return false;
            }
        }

        function clearAuth() {
            localStorage.removeItem('auth_token');
            checkAuth();
        }

        // 测试1: 获取收藏列表
        async function getBookmarks() {
            const token = localStorage.getItem('auth_token');
            if (!token) {
                showResult('bookmarksResult', '错误: 请先登录', 'error');
                return;
            }

            try {
                showResult('bookmarksResult', '正在获取收藏列表...', 'info');
                
                const response = await fetch('./api/bookmarks.php', {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                const responseText = await response.text();
                
                if (!response.ok) {
                    showResult('bookmarksResult', 
                        `HTTP错误: ${response.status}\n${responseText}`, 'error');
                    return;
                }

                try {
                    const data = JSON.parse(responseText);
                    const bookmarks = data.data?.bookmarks || [];
                    
                    let result = `成功获取 ${bookmarks.length} 个收藏:\n\n`;
                    bookmarks.forEach(bookmark => {
                        result += `ID: ${bookmark.id} - ${bookmark.name}\n`;
                    });
                    
                    showResult('bookmarksResult', result, 'success');
                } catch (parseError) {
                    showResult('bookmarksResult', 
                        `JSON解析错误: ${parseError.message}\n原始响应: ${responseText}`, 'error');
                }
            } catch (error) {
                showResult('bookmarksResult', `网络错误: ${error.message}`, 'error');
            }
        }

        // 测试2: 标准删除测试
        async function testDelete() {
            const bookmarkId = document.getElementById('bookmarkId').value;
            if (!bookmarkId) {
                showResult('deleteResult', '错误: 请输入收藏ID', 'error');
                return;
            }

            const token = localStorage.getItem('auth_token');
            if (!token) {
                showResult('deleteResult', '错误: 请先登录', 'error');
                return;
            }

            try {
                showResult('deleteResult', '正在删除收藏...', 'info');
                
                const response = await fetch('./api/bookmarks.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        action: 'delete',
                        id: parseInt(bookmarkId)
                    })
                });

                const responseText = await response.text();
                
                showResult('deleteResult', 
                    formatResponse(responseText, response.status, response.headers), 
                    response.ok ? 'success' : 'error'
                );

                // 尝试解析JSON
                try {
                    const data = JSON.parse(responseText);
                    if (data.success) {
                        showResult('deleteResult', 
                            `✅ 删除成功!\n消息: ${data.message}\n删除的ID: ${data.data?.deleted_id}`, 
                            'success'
                        );
                    } else {
                        showResult('deleteResult', 
                            `❌ 删除失败: ${data.message}`, 
                            'error'
                        );
                    }
                } catch (parseError) {
                    showResult('deleteResult', 
                        `JSON解析错误: ${parseError.message}\n原始响应: ${responseText}`, 
                        'error'
                    );
                }
            } catch (error) {
                showResult('deleteResult', `网络错误: ${error.message}`, 'error');
            }
        }

        // 测试3: 原始API测试
        async function testRawDelete() {
            const bookmarkId = document.getElementById('rawBookmarkId').value;
            if (!bookmarkId) {
                showResult('rawDeleteResult', '错误: 请输入收藏ID', 'error');
                return;
            }

            const token = localStorage.getItem('auth_token');
            if (!token) {
                showResult('rawDeleteResult', '错误: 请先登录', 'error');
                return;
            }

            try {
                showResult('rawDeleteResult', '正在进行原始API测试...', 'info');
                
                // 使用原始fetch，不处理任何错误
                const response = await fetch(`./api/bookmarks.php?action=delete&id=${bookmarkId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    }
                });

                const responseText = await response.text();
                
                let result = `=== 原始API响应 ===\n`;
                result += `状态码: ${response.status} ${response.statusText}\n`;
                result += `Content-Type: ${response.headers.get('content-type')}\n`;
                result += `响应长度: ${responseText.length} 字符\n\n`;
                result += `=== 响应头 ===\n`;
                for (const [key, value] of response.headers.entries()) {
                    result += `${key}: ${value}\n`;
                }
                result += `\n=== 响应体 ===\n${responseText}`;
                
                showResult('rawDeleteResult', result, response.ok ? 'success' : 'error');
            } catch (error) {
                showResult('rawDeleteResult', `原始API错误: ${error.message}`, 'error');
            }
        }

        // 测试4: 调试删除测试
        async function testDebugDelete() {
            const bookmarkId = document.getElementById('debugBookmarkId').value;
            if (!bookmarkId) {
                showResult('debugDeleteResult', '错误: 请输入收藏ID', 'error');
                return;
            }

            const token = localStorage.getItem('auth_token');
            if (!token) {
                showResult('debugDeleteResult', '错误: 请先登录', 'error');
                return;
            }

            try {
                showResult('debugDeleteResult', '正在进行调试删除测试...', 'info');
                
                const response = await fetch('./api/debug-delete.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${token}`
                    },
                    body: JSON.stringify({
                        action: 'delete',
                        id: parseInt(bookmarkId)
                    })
                });

                const responseText = await response.text();
                
                let result = `=== 调试删除API响应 ===\n`;
                result += `状态码: ${response.status} ${response.statusText}\n`;
                result += `Content-Type: ${response.headers.get('content-type')}\n`;
                result += `响应长度: ${responseText.length} 字符\n\n`;
                
                // 提取调试信息（HTML注释）
                const debugLines = responseText.split('\n').filter(line => line.includes('<!-- DEBUG:'));
                if (debugLines.length > 0) {
                    result += "=== 调试日志 ===\n";
                    debugLines.forEach(line => {
                        const startIdx = line.indexOf('<!-- DEBUG: ') + 12;
                        const endIdx = line.indexOf(' -->');
                        if (startIdx > 11 && endIdx > startIdx) {
                            const message = line.substring(startIdx, endIdx);
                            result += message + "\n";
                        }
                    });
                    result += "\n";
                }
                
                // 提取JSON响应
                const jsonMatch = responseText.match(/\{[\s\S]*\}/);
                if (jsonMatch) {
                    try {
                        const data = JSON.parse(jsonMatch[0]);
                        result += `=== JSON响应 ===\n${JSON.stringify(data, null, 2)}\n\n`;
                        
                        if (data.success) {
                            showResult('debugDeleteResult', result, 'success');
                        } else {
                            showResult('debugDeleteResult', result, 'error');
                        }
                    } catch (parseError) {
                        result += `=== JSON解析错误 ===\n${parseError.message}\n\n`;
                        showResult('debugDeleteResult', result, 'error');
                    }
                } else {
                    result += `=== 完整响应 ===\n${responseText}`;
                    showResult('debugDeleteResult', result, 'error');
                }
            } catch (error) {
                showResult('debugDeleteResult', `调试API错误: ${error.message}`, 'error');
            }
        }

        // 测试5: 连接测试
        async function testConnection() {
            showResult('connectionResult', '正在测试连接...', 'info');
            
            const tests = [
                { name: 'API基础连接', url: './api/bookmarks.php' },
                { name: 'CORS预检', url: './api/bookmarks.php', method: 'OPTIONS' },
                { name: '认证端点', url: './api/auth.php' }
            ];

            let results = '';
            
            for (const test of tests) {
                try {
                    const response = await fetch(test.url, {
                        method: test.method || 'GET'
                    });
                    
                    results += `✅ ${test.name}: ${response.status} ${response.statusText}\n`;
                } catch (error) {
                    results += `❌ ${test.name}: ${error.message}\n`;
                }
            }
            
            showResult('connectionResult', results, 'success');
        }

        // 页面加载时检查认证
        window.onload = function() {
            checkAuth();
        };
    </script>
</body>
</html>
